/**
 * 地图组建，
 * @width 地图的宽，单位rpx
 * @height 地图的高，单位rpx
 * scaleViewForPoints 地图缩放适应输入点，传入数组
 * distanceToDestin 当前用户到目标点的距离，可以传入数组
 * centerPoint 显示坐标点并居中，接受坐标点和缩放等级
 * markerPoints 在地图上标记点，接受坐标点数组
 * showPopupAboveCenter 在中心点上方显示气泡
 */

const QQMapWX = require('../../../lib/qqmap-wx-jssdk.min.js');
let qqmapsdk;
let mapCtx; // 地图实例
let globalData = getApp().globalData;
Component({
  properties: {
    mapKey: { // 地图插件的key
      type: String, // 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      value: '', // 属性初始值（可选），如果未指定则会根据类型选择一个
      observer(newVal, oldVal, changedPath) {
        if (newVal && newVal.length > 0 && !qqmapsdk) {
          qqmapsdk = new QQMapWX({
            key: newVal,
          });
        }
      }
    },
    withoutMapCtrl: Boolean,
  },

  /**
   * 组件的初始数据
   */
  data: {
    scale: 13, // 默认缩放
    includePoints: [],
    popupPositionAboveCenter: '',
    smallSize: 0,
  },

  lifetimes: {
    attached: function() {
      mapCtx = wx.createMapContext('mymap', this);
      if (globalData.userLocation) {
        this.setData({
          lat: globalData.userLocation.latitude,
          lng: globalData.userLocation.longitude,
          userLat: globalData.userLocation.latitude,
          userLng: globalData.userLocation.longitude,
        })
        this.triggerEvent('location', {
          location: {
            lat: globalData.userLocation.latitude,
            lng: globalData.userLocation.longitude,
          }
        }, {})
      } else {
        this.locationAndCenter();
      }
      this.setData({
        smallSize: this.rpxToPx(34),
      })
    },
    moved: function() {},
    detached: function() {},
  },
  /**
   * 组件的方法列表
   */
  methods: {
    rpxToPx: function(num) {
      const sysInfo = wx.getSystemInfoSync();
      return num / 750 * sysInfo.windowWidth;
    },
    locationAndCenter() {
      wx.getLocation({
        type: 'gcj02',
        altitude: true,
        success: (res) => {
          this.setData({
            lat: res.latitude,
            lng: res.longitude,
            userLat: res.latitude,
            userLng: res.longitude,
          });
          this.triggerEvent('location', {
            location: {
              lat: res.latitude,
              lng: res.longitude,
            }
          }, {})
        },
        fail: function(res) {
          wx.showToast({
            title: '定位失败',
            icon: 'none',
            duration: 1400,
            mask: false,
          })
        },
        complete: function(res) {},
      })
    },
    scaleCtrl(e) { // 放大缩小地图
      let _mapCtx = wx.createMapContext('mymap', this);

      const opt = e.currentTarget.dataset.opt;
      if (opt === '+') {
        _mapCtx.getScale({
          success: (d) => {
            if (d.errMsg === "getMapScale:ok") {
              this.setData({
                scale: d.scale + 1,
              })
            }
          },
          fail: (err) => {
            console.warn(err)
          },
        })
      } else {
        _mapCtx.getScale({
          success: (d) => {
            if (d.errMsg === "getMapScale:ok") {
              this.setData({
                scale: d.scale - 1,
              })
            }
          },
          fail: (err) => {
            console.warn(err)
          },
        })
      }
    },
    setPopupPosition() { // 设置弹窗的位置
      const sysInfo = wx.getSystemInfoSync();
      const displayRaito = sysInfo.pixelRatio;
      const relativePosition = 105; // 向上偏移量 px
      const query = wx.createSelectorQuery().in(this)
      query.select('.showmap').boundingClientRect();
      query.exec((res) => {
        const popupPositionAboveCenter = "left:" + this.rpxToPx(75) + 'px' + ';top:' + (res[0].height / 2 - relativePosition) + 'px';
        this.setData({
          popupPositionAboveCenter: popupPositionAboveCenter,
        })
      })
    },
    scaleViewForPoints(pointArray) {
      this.setData({
        includePoints: pointArray,
      })
    },
    distanceToDestin(point, success, fail, complete) {
      if (!this.data.userLat || !this.data.userLng) {
        return '起点信息缺失'
      }
      qqmapsdk.calculateDistance({
        from: {
          latitude: this.data.userLat,
          longitude: this.data.userLng
        },
        to: point,
        success: (d) => {
          success(d);
        },
        fail: (d) => {
          fail(d);
        },
        complete: () => {
          complete();
        },
      })
    },
    centerPoint(point, scale) {
      // console.log(point);
      this.setData({
        lat: point.latitude,
        lng: point.longitude,
      })
      if (scale) {
        this.setData({
          scale: scale,
        })
      }
    },
    showPopupAboveCenter(obj) {
      this.setPopupPosition(); // 弹窗位置
      this.setData({
        popupPositionAboveCenterShow: true,
        popupText: obj.name,
        popupText2: obj.address,
        popupLat: obj.latitude,
        popupLng: obj.longitude,
      });
    },
    markerPoints(points) {
      let _p = [];
      for (let i = 0; i < points.length; i++) {
        let obj = Object.assign(points[i]);
        obj.id = 'id' + i;
        obj.iconPath = '/assert/img/icon_location_small.png';
        obj.width = this.data.smallSize;
        obj.height = this.data.smallSize;
        _p.push(obj);
      }
      // console.log(_p)
      this.setData({
        markers: _p,
      })
    },
    markertap(e) {
      // console.log(e.markerId);
      if (this.data.withoutMapCtrl){
        return;
      }
      const id = e.markerId;
      for (let i of this.data.markers) {
        if (i.id === id) {          
          if (i.iconPath === '/assert/img/icon_location_big.png') {
            i.iconPath = '/assert/img/icon_location_small.png';
            i.width = this.data.smallSize;
            i.height = this.data.smallSize;
            i.callout = {};
          }else {
            i.width = this.rpxToPx(60);
            i.height = this.rpxToPx(71);
            i.iconPath = '/assert/img/icon_location_big.png';
            i.callout = {
              content: i.content,
              bgColor: "#000000d0",
              fontSize: this.rpxToPx(28),
              color: '#fff',
              display: 'ALWAYS',
              padding: this.rpxToPx(16),
              borderRadius: this.rpxToPx(8),
            }
          }
        } else {
          i.iconPath = '/assert/img/icon_location_small.png';
          i.width = this.data.smallSize;
          i.height = this.data.smallSize;
          i.callout = {};
        }
      }
      this.setData({
        markers: this.data.markers,
      })
    },
    showNavToTjz(e) {
      const targetLat = e.currentTarget.dataset.lat;
      const targetLng = e.currentTarget.dataset.lng;
      // console.log(targetLat, targetLng);
      wx.request({
        url: 'https://apis.map.qq.com/ws/direction/v1/bicycling',
        data: {
          key: this.data.mapKey,
          from: this.data.userLat + ',' + this.data.userLng,
          to: targetLat + ',' + targetLng,
        },
        header: {},
        method: 'GET',
        success: (res) => {
          if (res.data.message === "query ok") {
            const route = res.data.result.routes[0].polyline;
            let pl = [];
            var kr = 1000000;
            for (var i = 2; i < route.length; i++) {
              route[i] = Number(route[i - 2]) + Number(route[i]) / kr;
            }
            for (var i = 0; i < route.length; i += 2) {
              pl.push({
                latitude: route[i],
                longitude: route[i + 1]
              })
            }
            this.setData({
              polyline: [{
                points: pl,
                color: '#0078d4a5',
                width: 6,
                arrowLine: true,
              }],
              includePoints: pl,
              showPopup: false,
              popupPositionAboveCenterShow: false,
            })
          }
        },
        fail: function(res) {
          console.error(res)
        },
        complete: function(res) {},
      })
    },
    callouttap(e){
      const list = this.data.markers;
      for(let i of list){
        if( i.id === e.markerId){
          console.log(i)
          wx.navigateTo({
            url: './tijianDetail?name=' + i.content + '&addr=' + i.addr + '&location=' + i.latitude + ',' + i.longitude,
          })
          break;
        }
      }

    }
  }
})